/**   
 * @Title: PrAction.java 
 * @Package web.action 
 * @Description: PR相关Action入口 
 * @author 范庆辉 fanqinghui100@126.com   
 * @date 2013-4-16 上午11:16:09 
 * @version V1.0   
 *//*
package web.action.pr;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.tapestry.json.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import constant.Constant;
import exception.BusinessException;


import util.DateUtils;
import util.JsonUtil;
import util.List2JSON;
import util.LoggerUtils;
import util.file.ExcelReader;
import util.file.ExcelWriter;
import web.action.BasePageAction;

*//**
 * @ClassName: PrAction
 * @Description: PR逻辑类
 * @author 范庆辉 fanqinghui100@126.com
 * @date 2013-4-16 上午11:16:09
 *//*
@Scope("prototype")
@Controller
public class PurchaseRequestAction extends BasePageAction<PrListBulu> {
	private static final long serialVersionUID = 7517146068116962652L;

	*//**
	 * @Title: load
	 * @Description:加载pr-x页面
	 * @param @throws BusinessException 设定文件
	 * @return void 返回类型
	 * @throws
	 *//*
	public void query() throws BusinessException {
		try {
			// 根据参数查询x&y&z表数据
			JSONObject json_obj = new JSONObject();
			Long total = 0L;
			String[] cellName = new String[] { "index", "approvalDateStr", "purchaseNumber", "purchaseName", "project1", "project2", "vendorName", "dept", "bizline", "expenseType", "expenseSubtype", "purchaseAmount", "serviceBeginDate", "serviceEndDate", "userName", "approverDesc", "lastOct", "lastNov", "lastDec", "lastYear", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "year", "nextJan", "nextFeb", "nextMar", "nextApr", "nextMay", "nextJun", "nextJul", "nextAug", "nextSep", "nextOct", "nextNov", "nextDec", "nextYear", "remark" };
			Map<String, Object> params = getPageParams();
			Map<String, Object> map = new HashMap<>();
			if (prListBuluQuery != null) {
				map = doParamMap(params, prListBuluQuery);
				String prLine = (String) map.get("prLine");
				if (prLine == null || prLine.length() == 0) {
					map.put("prLine", initPrLine((String) map.get("model")));
				}
				String model = getRequestParamter("model");
				if (Constant.Z_FOCUS.equals(model)) {
					map.put("prType", "'FOCUS_EXPTYPE0101'");
				}
			}
		//	params.putAll(map);
			
					//setCurrentPageNumber(total);

					//prListBuluTotal = findTotal(params, model, viewName);
					//prListBuluTotalForPage = findTotalForPage(resultList, null, null, null, null, null, model, viewName);

					//json_obj = new List2JSON<PrListBulu>().toJSON(currentPageNo, total, currentTotal, resultList, "index", cellName);

			//printWriter(json_obj.toString());
		}catch (Exception e) {
			System.out.println(e);
			throw new BusinessException("获取Pr列表出错");
		}
	}


	*//**
	 * 
	 * @Title: load
	 * @Description: 进入x界面之前进行的逻辑检查
	 * @param @return
	 * @param @throws BusinessException 设定文件
	 * @return String 返回类型
	 * @throws
	 *//*
	public String load() throws BusinessException {
		
	}

	*//**
	 * @Title: importExcel
	 * @Description: ajax处理excel导入逻辑
	 * @return void 返回类型
	 * @throws
	 *//*
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void importExcel() throws IOException {
		Map<String, Object> map_map = new HashMap<>();
		
		ValidateInfo validateInfo = new ValidateInfo();
		validateInfo.setFileName(fileName);
		List prList = new ArrayList<>();
		BasePo basepo = null;
		Date viewDate = new Date();
		List<String> bigLizeNames = null;
		List<String> expenseTypeNames = null;
		List<String> subExpenseTypeNames = null;
		List<String> project1Names = null;
		String templateName = modelName(model);
		// step1.确定取值头跟位置
		int[] indexs = new int[] { 1, 3, 4, 7, 8, 9, 45};// 1pr单号 3项目1 4项目2 7业务线 8大类 9小类
		String[] params = new String[] { "purchaseNumber", "project1", "project2", "bizline", "expenseType", "expenseSubtype","remark" };
		// focus没有业务线
		if (model.equals(Constant.Z_FOCUS)) {
			indexs = new int[] { 1, 3, 4, 7, 8 ,44};// 1pr单号 3项目1 4项目2 7大类 8小类
			params = new String[] { "purchaseNumber", "project1", "project2", "expenseType", "expenseSubtype" ,"remark" };
		}

		
		try {
			ExcelReader reader = new ExcelReader(myexcel);
			List<Map<Integer, String>> sheetList = reader.getDataBySheet(0, 1);
			// 从每一行里提取 想要得到的数据
			for (Map<Integer, String> rowMap : sheetList) {// 遍历每一行数据
				Map<String, Object> row = new HashMap<>();
				for (int i = 0; i < indexs.length; i++) {
					row.put(params[i], rowMap.get(indexs[i]));
				}
				listMaps.add(row);
			}
			// 1从excel里获取数据
			int index = 1;// excel第二行开始
			for (Map<String, Object> map : listMaps) {
				map_map.putAll(map);
				// 2进行数据验证,检查prNumber为不为空，作为记录,存入到一个map中
				String project1 = (String) map.get("project1");
				String project2 = (String) map.get("project2");
				String bizline = (String) map.get("bizline");
				String expenseType = (String) map.get("expenseType");
				String expenseSubtype = (String) map.get("expenseSubtype");
				String remark = (String) map.get("remark");
				StringBuilder errorMsg = new StringBuilder("");
				String errorStr = new String();
				boolean errorFlag = false;
				
				 * map.remove("project1"); map.remove("project2");
				 
				// 验证prNumm是否为空
				if (map.get("purchaseNumber") == null || StringUtils.isBlank(map.get("purchaseNumber").toString())) {// 不包含小类
					errorMsg.append("PR单号不能为空！");
					errorFlag = true;
				}

				// 这里之前进行值集校验+(业务线-费用大类-费用小类)

				if (!model.equals(Constant.Z_FOCUS)) {// 不是焦点情况下需要验证业务线
					if (map.get("bizline") == null || StringUtils.isBlank(map.get("bizline").toString())) {// 业务线不为null
						errorMsg.append("业务线不能为空！");
						errorFlag = true;
					}
					else if (!bigLizeNames.contains(bizline)) {// 验证业务线是否为空
						errorMsg.append("业务线，");
						errorFlag = true;
					}
				}
				else if (!StringUtils.isNotBlank(project1)) {// 焦点项目1不能为空
					errorStr = "项目1不能为空！";
					errorFlag = true;
				}
				else if (StringUtils.isNotBlank(project1)) {// 焦点项目1不为空
					if (!project1Names.contains(project1)) {// 不包含项目1
						errorMsg.append("项目1，");
						errorFlag = true;
					}
				}

				// 验证大类
				if (map.get("expenseType") == null || StringUtils.isBlank(map.get("expenseType").toString())) {// 不包含小类
					errorMsg.append("费用大类不能为空！");
					errorFlag = true;
				}
				else {
					if (!expenseTypeNames.contains(expenseType)) {// 不包含大类
						errorMsg.append("费用大类，");
						errorFlag = true;
					}
				}
				// 验证小类（ps：汽车，视频 小类可以是NULL）
				if (map.get("expenseSubtype") == null || StringUtils.isBlank(map.get("expenseSubtype").toString())) {// 不包含小类
					if (model.equals(Constant.Z_SOHU) || model.equals(Constant.Z_FOCUS)) {
						errorMsg.append("费用小类不能为空！");
						errorFlag = true;
					}
				}
				else {
					if (!subExpenseTypeNames.contains(expenseSubtype)) {// 不包含小类
						errorMsg.append("费用小类，");
						errorFlag = true;
					}
				}

				if (errorFlag) {
					if (errorMsg.length() > 0) {
						validateInfo.put(index, errorStr + errorMsg + "不属于" + templateName + "模板值集");
					}
					else {
						validateInfo.put(index, errorStr);
					}
				}
				else {// 值集验证完毕.继续进行非空验证
					map_map.put("model", model);
					PrListBulu bulu = purchaseRequestService.queryByIds(map_map);
					if (bulu != null) {
						prList.add(pur_manage.doXSaveZ(bulu, basepo, project1, project2, yearName, sence, version, viewDate, remark));
					}
					else {
						String message = "表里没有此行记录：pr单号：" + map.get("purchaseNumber") + "-业务线：" + map.get("bizline") + " 费用大类：" + map.get("expenseType") + " 费用小类：" + map.get("expenseSubtype");
						if (model.equals(Constant.Z_FOCUS)) {
							message = "表里没有此行记录：pr单号：" + map.get("purchaseNumber") + "费用大类：" + map.get("expenseType") + " 费用小类：" + map.get("expenseSubtype");
						}
						validateInfo.put(index, message);
						// flag = false;
					}
				}
				index++;
			}
			
			validateInfo.setDataCount(prList.size());
			if (prList.size() > 0) {// 调用存储过程-同步记录
				// purchaseRequestService.callProduce(viewName);
				purchaseRequestService.callProduceByModel(viewName, model, "IMPORT");
				// 操作日志记录
				systemFunctionService.insertLogs(modelName(model), Constant.IMPORT_BTN, templateName(model, viewName), prList.size());
			}

		}
		catch (Exception e) {
			validateInfo.setDataCount(0);
			System.out.println(e);
		}
		printWriter(JsonUtil.toJson(validateInfo.asResult()), "text/html;charset=utf-8");
	}

	

	*//**
	 * 
	 * @Title: export
	 * @Description: 导出excel
	 * @param @return
	 * @param @throws Exception 设定文件
	 * @return String 返回类型
	 * @throws
	 *//*
	@SuppressWarnings("rawtypes")
	public String export() throws Exception {
		// System.out.println(model);
		String[] headers, keys;
		String yearSenceVer = "";
		int count = 0;
		model = getRequestParamter("model");
		viewName = getRequestParamter("viewName");
		fileName = templateName(model, viewName);
		headers = new String[] { "审核日期", "PR单号", "PR单说明", "项目1", "项目2", "供应商", "部门", "业务线", "费用大类", "费用小类", "申请金额", "服务范围From", "服务范围To", "更新人", "财务备注", "上一年度10月", "上一年度11月", "上一年度12月", "以前年度合计", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月", "本年合计", "下一年度1月", "下一年度2月", "下一年度3月", "下一年度4月", "下一年度5月", "下一年度6月", "下一年度7月", "下一年度8月", "下一年度9月", "下一年度10月", "下一年度11月", "下一年度12月", "下一年度合计", "备注" };
		keys = new String[] { "approvalDate", "purchaseNumber", "purchaseName", "project1", "project2", "vendorName", "dept", "bizline", "expenseType", "expenseSubtype", "purchaseAmount", "serviceBeginDate", "serviceEndDate", "userName", "approverDesc", "lastOct", "lastNov", "lastDec", "lastYear", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "year", "nextJan", "nextFeb", "nextMar", "nextApr", "nextMay", "nextJun", "nextJul", "nextAug", "nextSep", "nextOct", "nextNov", "nextDec", "nextYear", "remark" };
		ExcelWriter writer = null;
		// 根据参数导出x表数据
		// Map<String, Object> map = getPageParams();
		Map<String, Object> params = new HashMap<>();
		if (prListBuluQuery != null) {
			params = doParamMap(params, prListBuluQuery);
			String prLine = (String) params.get("prLine");
			if (prLine == null || prLine.length() == 0) {
				params.put("prLine", initPrLine((String) params.get("model")));
			}
			if (Constant.Z_FOCUS.equals(model)) {
				params.put("prType", "'FOCUS_EXPTYPE0101'");// 确认只查找A&P
			}
			yearSenceVer = "（" + prListBuluQuery.getYearName() + "." + prListBuluQuery.getSence() + "." + prListBuluQuery.getVersion() + "）";
		}

		// 设置排序
		String sortname = getRequestParamter("sortname");
		String sortorder = getRequestParamter("sortorder");
		params.put("orderBy", sortname);
		params.put("order", sortorder);

		// params.putAll(map);
		switch (model) {
			case Constant.Z_FOCUS:
				headers = new String[] { "审核日期", "PR单号", "PR单说明", "项目1", "项目2", "供应商", "部门", "费用大类", "费用小类", "申请金额", "服务范围From", "服务范围To", "更新人", "财务备注", "上一年度10月", "上一年度11月", "上一年度12月", "以前年度合计", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月", "本年合计", "下一年度1月", "下一年度2月", "下一年度3月", "下一年度4月", "下一年度5月", "下一年度6月", "下一年度7月", "下一年度8月", "下一年度9月", "下一年度10月", "下一年度11月", "下一年度12月", "下一年度合计", "备注" };
				keys = new String[] { "approvalDate", "purchaseNumber", "purchaseName", "project1", "project2", "vendorName", "dept", "expenseType", "expenseSubtype", "purchaseAmount", "serviceBeginDate", "serviceEndDate", "userName", "approverDesc", "lastOct", "lastNov", "lastDec", "lastYear", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "year", "nextJan", "nextFeb", "nextMar", "nextApr", "nextMay", "nextJun", "nextJul", "nextAug", "nextSep", "nextOct", "nextNov", "nextDec", "nextYear", "remark" };
				break;
		}
		// 2
		switch (viewName) {
			case "x":// ok
				params.put("flag", Constant.FLAG_YES);
				List<PrListBulu> listX = purchaseRequestService.queryPage(params);
				count = listX.size();
				writer = new ExcelWriter("导出X表数据", headers, keys, listX);
				break;
			case "y":// 5.3
				if (model.equals(Constant.Z_FOCUS)) {// 无业务线
					keys = new String[] { "approval_date", "purchase_number", "purchase_name", "project1", "project2", "vendor_name", "dept", "expense_type", "expense_subtype", "purchase_amount", "service_begin_date", "service_end_date", "user_name", "approver_desc", "last_oct", "last_nov", "last_dec", "last_year", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "year", "next_jan", "next_feb", "next_mar", "next_apr", "next_may", "next_jun", "next_jul", "next_aug", "next_sep", "next_oct", "next_nov", "next_dec", "next_year", "remark" };
				}
				else {
					keys = new String[] { "approval_date", "purchase_number", "purchase_name", "project1", "project2", "vendor_name", "dept", "bizline", "expense_type", "expense_subtype", "purchase_amount", "service_begin_date", "service_end_date", "user_name", "approver_desc", "last_oct", "last_nov", "last_dec", "last_year", "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", "year", "next_jan", "next_feb", "next_mar", "next_apr", "next_may", "next_jun", "next_jul", "next_aug", "next_sep", "next_oct", "next_nov", "next_dec", "next_year", "remark" };
				}
				List<PrListBuluDiff> listY = purchaseRequestDiffService.queryPage(params);
				count = listY.size();
				writer = new ExcelWriter("导出Y表数据", headers, keys, listY);
				break;
			case "z":// 4.25
				headers = new String[] { "审核日期", "PR单号", "PR单说明", "项目1", "项目2", "供应商", "部门", "业务线", "费用大类", "费用小类", "申请金额", "服务范围From", "服务范围To", "财务备注", "上一年度10月", "上一年度11月", "上一年度12月", "以前年度合计", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月", "本年合计", "下一年度1月", "下一年度2月", "下一年度3月", "下一年度4月", "下一年度5月", "下一年度6月", "下一年度7月", "下一年度8月", "下一年度9月", "下一年度10月", "下一年度11月", "下一年度12月", "下一年度合计", "备注" };
				keys = new String[] { "approvalDate", "purchaseNumber", "purchaseName", "projectName1", "projectName2", "vendorName", "deptName", "bizline", "expenseType", "expenseSubtype", "purchaseAmount", "serviceBeginDate", "serviceEndDate", "approverDesc", "last10", "last11", "last12", "lastQ4", "this01", "this02", "this03", "this04", "this05", "this06", "this07", "this08", "this09", "this10", "this11", "this12", "thisTotal", "next01", "next02", "next03", "next04", "next05", "next06", "next07", "next08", "next09", "next10", "next11", "next12", "nextTotal", "ps" };
				List list = null;
				switch (getRequestParamter("model")) {
					case Constant.Z_CAR:
						list = bgCarPrService.queryPage(params);
						break;
					case Constant.Z_SOHU:
						list = bgSohuPrService.queryPage(params);
						break;
					case Constant.Z_VIDEO:
						list = bgVideoPrService.queryPage(params);
						break;
					case Constant.Z_FOCUS:// remove bizLine
						headers = new String[] { "审核日期", "PR单号", "PR单说明", "项目1", "项目2", "供应商", "部门", "费用大类", "费用小类", "申请金额", "服务范围From", "服务范围To", "财务备注", "上一年度10月", "上一年度11月", "上一年度12月", "以前年度合计", "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月", "本年合计", "下一年度1月", "下一年度2月", "下一年度3月", "下一年度4月", "下一年度5月", "下一年度6月", "下一年度7月", "下一年度8月", "下一年度9月", "下一年度10月", "下一年度11月", "下一年度12月", "下一年度合计", "备注" };
						keys = new String[] { "approvalDate", "purchaseNumber", "purchaseName", "projectName1", "projectName2", "vendorName", "deptName", "expenseType", "expenseSubtype", "purchaseAmount", "serviceBeginDate", "serviceEndDate", "approverDesc", "last10", "last11", "last12", "lastQ4", "this01", "this02", "this03", "this04", "this05", "this06", "this07", "this08", "this09", "this10", "this11", "this12", "thisTotal", "next01", "next02", "next03", "next04", "next05", "next06", "next07", "next08", "next09", "next10", "next11", "next12", "nextTotal", "ps" };
						list = bgFocusPrService.queryPage(params);
						break;
				}
				if (list != null) {
					count = list.size();
					writer = new ExcelWriter(fileName, headers, keys, list);
				}
				break;
		}
		// 操作日志记录
		systemFunctionService.insertLogs(modelName(model), Constant.EXPORT_BTN, fileName, count);
		fileName += "-导出数据" + yearSenceVer + ".xlsx";
		fileName = URLEncoder.encode(fileName, "UTF-8");
		if (writer != null) {
			inputStream = writer.newInputStream();
		}
		return "excel";
	}




	*//**
	 * 函数名称: parseData 函数描述: 将json字符串转换为map
	 * 
	 * @param data
	 * @return
	 *//*
	@SuppressWarnings("unused")
	private Map<String, Object> jsonToMap(String data) {
		GsonBuilder gb = new GsonBuilder();
		Gson g = gb.create();
		Map<String, Object> map = g.fromJson(data, new TypeToken<Map<String, Object>>() {
		}.getType());
		return map;
	}

	*//**
	 * @Description: bean to Map
	 * @param @param obj
	 * @return Map<String,Object> 返回类型
	 * @throws
	 *//*
	private Map<String, Object> transBean2Map(Object obj) {
		if (obj == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				// 过滤class属性
				if (!key.equals("class")) {
					// 得到property对应的getter方法
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);
					map.put(key, value);
				}
			}
		}
		catch (Exception e) {
			System.out.println("transBean2Map Error " + e);
		}
		return map;
	}

	
	*//**
	 * 绕过Template,直接输出内容的简便函数.
	 *//*
	protected void renderText(String text) {
		render(text, "text/plain;charset=UTF-8");
	}

	*//**
	 * 绕过Template,直接输出内容的简便函数.
	 *//*
	protected void render(String text, String contentType) {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType(contentType);
			response.getWriter().write(text);
		}
		catch (IOException e) {
			System.out.println(e);
		}
	}

	



	

}*/